import * as ts from 'typescript';
const path = require('path');
const fs = require('fs');

const compiler = {
	target: ts.ScriptTarget.ES5,
	noEmitOnError: true,
	module: ts.ModuleKind.CommonJS,
};

const file = 'src/plugins/sw2ts.ts';

export const apply = () => {
	const c = process.cwd();
	const f = path.resolve(c, file);
	if (fs.existsSync(f)) {
		const fn = require(f);
		return Array.isArray(fn) ? fn : [fn];
	} else {
		return [];
	}
};

export const getSourceFile = (file: string, options?: ts.CompilerOptions) => {
	const t = path.resolve(__dirname, file);

	return ts
		.createProgram({
			rootNames: [t],
			options: options ?? compiler,
		})
		.getSourceFile(t);
};

